﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion.DynamicApiController;

namespace Abc.Application.HtAdminServices;

/// <summary>
/// 事件源存储器
/// </summary>
public class HtEventSourceStorerService : IHtEventSourceStorerService, ITransient
{
    private readonly ILogger<HtEventSourceStorerService> _logger;
    private readonly ISqlSugarClient _db;

    public HtEventSourceStorerService(ILogger<HtEventSourceStorerService> logger
     , ISqlSugarClient db = null)
    {
        _logger = logger;
        _db = db;
    }

    /// <summary>
    /// 新增或更新一条
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<long> Insert(HtEventSourceStorerInput input)
    {
        ////验证 父级下 唯一 Key是否存在
        //var isexit = await _db.Queryable<SysEventSourceStorer>().AnyAsync(o => o.PKey == input.PKey && o.Key == input.Key);
        //if (isexit)
        //{
        //    throw Oops.Bah("唯一标识Key不能重复");
        //}
        var addentity = input.Adapt<SysEventSourceStorer>();
        return await _db.InsertRsIdAsync(addentity);
    }

    /// <summary>
    /// 更新一条
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<bool> Update(HtEventSourceStorerInput input)
    {
        ////验证 父级下 唯一 Key是否存在
        //var isexit = await _db.Queryable<SysEventSourceStorer>().AnyAsync(o => o.PKey == input.PKey && o.Key == input.Key && o.Id != input.Id);
        //if (isexit)
        //{
        //    throw Oops.Bah("唯一标识Key不能重复");
        //}
        var dbentity = await _db.Queryable<SysEventSourceStorer>().FirstAsync(o => o.Id == input.Id.Value);
        input.Adapt(dbentity);
        return await _db.UpdateAsync(dbentity);
    }

    /// <summary>
    /// 删除一条
    /// </summary>
    /// <param name="id"></param>
    public async Task<bool> Delete(long id)
    {
        if (id <= 0) throw Oops.Bah("id不能为0");
        return await _db.DeleteByIdAsync<SysEventSourceStorer>(id);
    }

    /// <summary>
    /// 批量删除
    /// </summary>
    /// <param name="ids">需要删除的数据，多条以英文逗号隔开</param>
    public async Task<bool> BatchDelete(string ids)
    {
        return await _db.DeleteByIdsAsync<SysEventSourceStorer>(ids);
    }

    /// <summary>
    /// 查询一条
    /// </summary>
    /// <param name="id"></param>
    public async Task<HtEventSourceStorerOut> Get(long id)
    {
        return await _db.GetByIdAsync<SysEventSourceStorer, HtEventSourceStorerOut>(id);
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="searchQuery"></param>
    /// <returns></returns>
    public async Task<LayuiPagedList<HtEventSourceStorerOut>> GetAllByPageToLayui(HtEventSourceStorerQuery searchQuery)
    {
        var queryable = _db.Queryable<SysEventSourceStorer>();

        #region 筛选条件

        //开始日期
        if (searchQuery.StartDate.HasValue)
        {
            queryable = queryable.Where(o => o.CreationTime >= searchQuery.StartDate.Value);
        }
        //结束日期
        if (searchQuery.EndDate.HasValue)
        {
            var endtime = Convert.ToDateTime($"{searchQuery.EndDate.Value:yyyy-MM-dd} 23:59:59");
            queryable = queryable.Where(o => o.CreationTime <= endtime);
        }
        // 事件处理状态
        if (searchQuery.State.HasValue)
        {
            queryable = queryable.Where(o => o.State == searchQuery.State.Value);
        }
        // 事件 Id
        if (searchQuery.EventId.HasValue)
        {
            var eventId = EventBusHelper.Instance.GetEventId(searchQuery.EventId.Value);
            queryable = queryable.Where(o => o.EventId == eventId);
        }
        //关键词
        if (string.IsNullOrWhiteSpace(searchQuery.KeyWords))
        {
            var kw = searchQuery.KeyWords?.Trim()?.ToLower() ?? "";
            queryable = queryable.Where(o => o.Payload.Contains(kw));
        }

        #endregion 筛选条件

        queryable = queryable.OrderByDescending(o => o.Id);
        var pagelist = await queryable.Select(o => new HtEventSourceStorerOut()
        {
            Id = o.Id.SelectAll(),

            #region 自定义
            #endregion
        })
        .Mapper(src =>
        {
            src.StateName = src.State.ToString();
        })
        .ToLayuiPagedListAsync(searchQuery.Page, searchQuery.Limit);

        return pagelist;
    }

    /// <summary>
    /// 设置状态
    /// </summary>
    /// <param name="id"></param>
    /// <param name="state"></param>
    /// <param name="field">字段名</param>
    /// <returns></returns>
    public async Task<bool> SetState(long id, bool state, string field)
    {
        return await _db.SetStateByIdAsync<SysEventSourceStorer>(id, state, field);
    }

    #region 冗余方法

    ///// <summary>
    ///// 假删除
    ///// </summary>
    ///// <param name="id"></param>
    //public async Task<bool> FakeDelete(long id)
    //{
    //    return await _db.FakeDeleteAsync<SysEventSourceStorer>($"{id}");
    //}

    ///// <summary>
    ///// 批量假删除
    ///// </summary>
    ///// <param name="ids">需要删除的数据，多条以英文逗号隔开</param>
    //public async Task<bool> BatchFakeDelete(string ids)
    //{
    //    return await _db.FakeDeleteAsync<SysEventSourceStorer>(ids);
    //}

    #endregion 冗余方法

}